<template>
  <div class="table">
    <div class="table_top">
      <div class="table_top_L">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="联赛id">
            <el-select v-model="formInline.contestId" placeholder="联赛id" clearable @change="changeContest">
              <el-option v-for="option in tableData1" :key="option.value" :label="option.label" :value="option.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="球队id">
            <el-select v-model="formInline.teamId" placeholder="请先选择联赛id" clearable :disabled="!formInline.contestId">
              <el-option :label="item.teamName" :value="item.id" v-for="item in playerTeamData" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="球员id">
            <el-input v-model="formInline.playerId" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="球员名称">
            <el-input v-model="formInline.playerName" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="inquire">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="importTable">导入</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="movingTeam">迁移球队</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-table
      :data="tableData"
      width="10%"
      height="100%"
      border
      stripe
      highlight-current-row
      v-loading="listLoading"
      ref="table"
      current-row-key="id"
      row-key="id"
      key="id"
      column-key="id"
      @selection-change="selectionChange"
    >
      <el-table-column prop="id" label="球员id" width="80"></el-table-column>
      <el-table-column prop="playerTeamName" label="球队名称"></el-table-column>
      <el-table-column prop="name" label="球员名称"></el-table-column>
      <el-table-column prop="playerNumber" label="球员编号"></el-table-column>
      <el-table-column label="性别">
        <template slot-scope="scope">
          <span>{{ scope.row.sex == 0 || !scope.row.sex ? '男' : '女' }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 导入弹窗 -->
    <el-dialog :visible.sync="bindVisible" title="导入数据" @close="onCloseBind" @opened="dialogOpened">
      <el-form :inline="true">
        <el-form-item label="联赛id">
          <el-select v-model="importObj.contestId" placeholder="联赛id" clearable @change="getTeamList(importObj.contestId)">
            <el-option v-for="option in tableData1" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="球队id">
          <el-select v-model="importObj.teamId" placeholder="请先选择联赛id" clearable>
            <el-option :label="item.teamName" :value="item.id" v-for="item in playerTeamData" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="download" style="margin: 20px 0;">下载模板文件</el-button>
      <div>
        <el-link type="warning" :underline="false">请先选择联赛和球队，然后下载模版文件编辑文件后再导入，否则可能会失败！</el-link>
      </div>
      <uploadExcel
        label="导入文件"
        :params="{ contestId: importObj.contestId, teamId: importObj.teamId }"
        style="margin-top: 15px"
        @ok="getResult"
      />
      <div v-if="errMsg">{{ errMsg }}</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="bindVisible = !bindVisible">取 消</el-button>
        <el-button type="primary" @click="submitSure">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="uploadPhotoDialogVisible" title="上传图片" @close="resetUploadPhoto">
      <el-form :model="newBanner" ref="addForm">
        <el-form-item label="图片" prop="img">
          <div v-loading="isLoading" element-loading-text="正在上传...">
            <div v-for="(url, index) in uploadUrl" :key="index">
              <img v-if="url" :src="url" style="height:100px;width:100px;margin-right:10px;" />
            </div>
            <input type="file" multiple @change="handleFileChange" ref="fileInput" />
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closePhotoDialog">取 消</el-button>
        <el-button type="primary" @click="uploadPhotos">确 定</el-button>
      </span>
    </el-dialog>
    <div class="table_bottom">
      <el-pagination @current-change="paginationChange" small background layout="prev, pager, next" :total="total" :page-size="20">
      </el-pagination>
    </div>

    <el-dialog :visible.sync="movingTeamDialogVisible" title="迁移球队" @close="movingTeamDialogVisible = false" width="500px">
      <el-form :model="newBanner" ref="addForm">
        <el-form-item label="迁移联赛">
          <el-select v-model="movingTeamObj.contestId" placeholder="迁移联赛" clearable filterable @change="changeContest">
            <el-option v-for="option in tableData1" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="迁移球队">
          <el-select v-model="movingTeamObj.teamId" placeholder="迁移球队" clearable filterable :disabled="!movingTeamObj.contestId">
            <el-option :label="item.teamName" :value="item.id" v-for="item in playerTeamData" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目标联赛">
          <el-select v-model="movingTeamObj.targetContestId" placeholder="目标联赛" clearable filterable>
            <el-option v-for="option in tableData1" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="movingTeamDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="movingTeamSure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  playerList,
  contestListDown,
  playerTeamList,
  auditStatusPost,
  uploadPhoto,
  uploadPhotos,
  getContestBinding,
  contestBinding,
  importPlayerApi,
  movePlayer
} from '../../api/table.js'
import uploadExcel from '@/components/uploadExcel.vue'

export default {
  components: { uploadExcel },
  data() {
    return {
      tableData1: [],
      playerTeamData: [],

      bingContestName: '',
      bindingData: [],
      bindVisible: false,
      bindSelection: [],
      originId: '',
      bindLoading: false,
      //
      uploadPhotoDialogVisible: false,
      fileList: [],
      tableData: [],
      listLoading: true,
      isLoading: false,
      uploadUrl: [],
      newBanner: {
        img: ''
      },
      selectRowId: 0,
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      photoFileList: '',
      formInline: {},
      total: 0, // 添加总条数
      importObj: {},
      errMsg: '',
      movingTeamObj: {},
      movingTeamDialogVisible: false
    }
  },
  mounted() {
    this.reqData1()
    this.tableData = this.reqData()
    this.listLoading = false
  },
  methods: {
    movingTeam() {
      this.movingTeamDialogVisible = true
      this.movingTeamObj = {}
    },
    movingTeamSure() {
      movePlayer(this.movingTeamObj).then(res => {
        console.log('res', res)
        if (res.code == 200) {
          this.movingTeamDialogVisible = false
          this.$message.success('操作成功')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    submitSure() {
      const formData = new FormData()
      formData.append('file', this.importObj.file) // 'file'是服务器接收文件的字段名
      formData.append('contestId', this.importObj.contestId)
      formData.append('teamId', this.importObj.teamId)
      let that = this
      importPlayerApi(formData)
        .then(res => {
          if (res.code == 200) {
            that.errMsg = ''
            this.$message.success(res.msg)
            this.importObj.file = undefined
            this.bindVisible = !this.bindVisible
            this.inquire()
          }
        })
        .catch(err => {
          that.errMsg = err
          console.log('err', err)
        })
    },
    importTable() {
      this.bindVisible = true
    },
    getResult(e) {
      console.log('e', e)
      this.importObj.file = e
    },
    download() {
      let href = 'https://boyubasketball.oss-cn-shanghai.aliyuncs.com/1734106722866%E7%90%83%E5%91%98%E5%AF%BC%E5%85%A5.xlsx'
      window.open(href, '_blank')
    },
    onCloseBind() {
      this.bindVisible = false
    },
    onBinding(id) {
      this.originId = id
      this.bindLoading = true
      getContestBinding({ id, contestName: this.bingContestName })
        .then(res => {
          this.bindingData = res.data
          this.bindVisible = true
        })
        .finally(() => {
          this.bindLoading = false
        })
    },
    dialogOpened() {
      // 在对话框完全打开后执行勾选操作
      for (let i = 0; i < this.bindingData.length; i++) {
        if (this.bindingData[i].contestFlag) {
          this.$refs.multipleTable.toggleRowSelection(this.bindingData[i])
        }
      }
    },
    handleSelectionChange(val) {
      console.log('val', val)
      this.bindSelection = val
    },
    bindSure() {
      contestBinding({
        id: this.originId,
        ids: this.bindSelection.map(item => item.id)
      }).then(() => {
        this.$message.success('绑定成功')
        this.bindVisible = false
      })
    },
    //
    async handleFileChange(event) {
      const file = event.target.files[0]
      if (!file) return

      this.isLoading = true // 开始加载

      // 使用 FileReader 来读取文件并生成预览图
      const fileReader = new FileReader()
      fileReader.onload = e => {
        this.uploadUrl.push(e.target.result) // 添加文件的base64 URL
      }
      fileReader.readAsDataURL(file)

      const formData = new FormData()
      formData.append('file', file) // 'file' 为后端接收的字段名

      try {
        const response = await uploadPhoto(formData)
        console.log(response)
        if (this.photoFileList === '') {
          this.photoFileList += response.msg
        } else {
          this.photoFileList = this.photoFileList + ',' + response.msg
        }
        console.log('this.photoFileList:' + this.photoFileList)
        this.newBanner.img = response.msg
        this.$message.success('图片上传成功！')
      } catch (error) {
        this.$message.error('图片上传失败！')
      } finally {
        this.isLoading = false // 上传完成，结束加载
      }
    },

    openUploadPhotoDialog(rowId) {
      this.uploadPhotoDialogVisible = true
      this.selectRowId = rowId
    },

    closePhotoDialog() {
      this.uploadPhotoDialogVisible = false
      this.photoFileList = ''
      this.newBanner.img = ''
      this.uploadUrl = []
    },

    resetUploadPhoto() {
      this.photoFileList = ''
      this.newBanner.img = ''
      this.uploadUrl = []
    },

    async uploadPhotos() {
      // 处理上传成功的逻辑
      let params = {
        id: this.selectRowId,
        banner: this.photoFileList
      }
      const resp = await uploadPhotos(params)
      console.log('上传轮播图：' + resp)
      this.uploadPhotoDialogVisible = false
      this.newBanner.img = ''
    },

    inquire() {
      // 调用表格数据接口，传入查询参数
      this.reqData(1, 20, {
        ...this.formInline
      })
    },
    selectionChange(selection) {
      this.selectionLength = selection.length
    },
    handleClick(row) {
      this.dialogTitle = row ? '修改' : '新增'
      this.dialogFormVisible = true
    },
    // 分切改变，返回页码
    paginationChange(page) {
      this.listLoading = true
      this.reqData(page, 20, this.formInline) // 传入当前页码和每页显示的数据量
      this.$nextTick(() => {
        this.listLoading = false
        this.$refs.table.bodyWrapper.scrollTop = 0
      })
    },
    // 请求
    reqData(pageNum = 1, pageSize = 20, query = {}) {
      const params = { pageNum, pageSize, ...query }
      playerList(params).then(res => {
        this.tableData = res.rows
        this.total = res.total // 设置总条数
      })
    },
    reqData1(pageNum = 1, pageSize = 10000, query = {}) {
      const params = { pageNum, pageSize, ...query }
      contestListDown(params).then(res => {
        this.tableData1 = res.data.map(item => ({
          value: item.id,
          label: item.name // 假设 id 是数字类型
        }))
      })
    },
    changeContest(e) {
      if (e) {
        this.getTeamList(e)
      } else {
        this.formInline.teamId = ''
        this.playerTeamData = []
      }
    },
    getTeamList(contestId = 104) {
      playerTeamList({
        contestId,
        pageSize: 9999,
        pageNum: 1
      }).then(res => {
        console.log('res', res)
        this.playerTeamData = res.rows
        // if (res.rows.length) {
        //   this.formInline.teamId = res.rows[0].id || ''
        // }
      })
    },
    del(actionType, id) {
      const auditStatus = actionType === '通过' ? 1 : 2 // 1 for pass, 2 for fail
      const data = {
        id: id,
        auditStatus: auditStatus
      }

      this.$confirm(`比赛状态更改为${auditStatus === 1 ? '审核通过' : '审核失败'}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          auditStatusPost(data).then(res => {
            console.log(res, 'res=======----')
            this.$message({
              type: 'success',
              message: `状态更改为${auditStatus === 1 ? '审核通过' : '审核失败'}成功!`
            })
            this.tableData = this.reqData() // 刷新表格数据
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.table {
  display: flex;
  flex-flow: column;
  box-sizing: border-box;

  .table_top {
    display: flex;
    justify-content: space-between;
    padding-bottom: 10px;

    .table_top_L {
      text-align-last: left;
      flex: 1;
      overflow: hidden;
    }
  }

  .table_bottom {
    margin-top: 10px;
  }

  height: 100%;
}
</style>
<style>
.table .el-table {
  transition: all ease-in-out 0.3s;
}

.table .el-table td,
.table .el-table th {
  text-align: center;
}

.table .el-dialog {
  text-align: left;
}

.table .el-dialog .line {
  text-align: center;
}

.el-image-viewer__close {
  background-color: #fff;
}

/* 重新覆盖原来的样式，原来的样式是.el-drawer获取焦点时的outline */
.el-image-viewer__wrapper:focus {
  outline: none;
}
</style>
